package org.rcgwt.client.ui.validator.impl;

import org.rcgwt.client.ui.validator.IClientValidatorContext;
import org.rcgwt.client.ui.validator.IFormatter;
import org.rcgwt.client.ui.validator.ISingleton;
import org.rcgwt.client.ui.validator.IValidatorElement;

/**
 * A digital formatter which formats digit as group of 3 digits (1 000 000)
 * 
 * @author Elian ORIOU
 * 
 */

public class DigitalSpaceFormatter implements IFormatter, ISingleton {

	private static final DigitalSpaceFormatter INSTANCE = new DigitalSpaceFormatter();

	protected DigitalSpaceFormatter() {

	}

	@Override
	public String format(IClientValidatorContext context, String ttf) {
		String prebuffer = "";
		String buffer = "";
		/* If the digits is structured like 1000000 ==> 1 000 000 */
		if (!ttf.contains(".")) {
			int cpt = 0;
			for (int i = ttf.length() - 1; i >= 0; i--) {
				prebuffer = buffer;
				buffer = addFirstCharacter(prebuffer, ttf.charAt(i));
				cpt++;
				if (cpt == 3 && i != 0) {
					prebuffer = buffer;
					buffer = addFirstCharacter(prebuffer, ' ');
					cpt = 0;
				}
			}
		}
		/* If the digits is structured like 1000.220 ==> 1 000.220 */
		else {
			/* The operation is centered on the dot */
			int pointIndex = ttf.indexOf(".");
			String leftPart = ttf.substring(0, pointIndex);
			String rightPart = ttf.substring(pointIndex);

			int cpt = 0;
			for (int i = leftPart.length() - 1; i >= 0; i--) {
				prebuffer = buffer;
				buffer = addFirstCharacter(prebuffer, leftPart.charAt(i));
				cpt++;
				if (cpt == 3 && i != 0) {
					prebuffer = buffer;
					buffer = addFirstCharacter(prebuffer, ' ');
					cpt = 0;
				}
			}
			buffer += rightPart;
		}
		return buffer;
	}

	/**
	 * Add a character at the beginning of a string
	 * 
	 * @param str
	 *            The string to modify
	 * @param c
	 *            The character to add
	 * @return The string modified
	 */
	private String addFirstCharacter(String str, char c) {
		String s = c + str;
		return s;
	}

	public static IValidatorElement getInstance() {
		return INSTANCE;
	}

}
